using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class ItemMgr
{
	public delegate void OnUseItemHandler(Item item);

	public const string ITEM_FILE = "item.dat";

	private List<Item> _items = new List<Item>();

	private static ItemMgr _instance;

	public List<Item> items => _items;

	public static ItemMgr instance
	{
		get
		{
			if (_instance == null)
			{
				_instance = new ItemMgr();
				_instance.Load();
				if (!PlayerPrefs.HasKey("FirstOpenTime"))
				{
					PlayerPrefs.SetString("FirstOpenTime", DateTime.Now.ToString());
					for (int i = 2; i < 5; i++)
					{
						_instance.AddItem(i, 3);
					}
				}
			}
			return _instance;
		}
	}

	public event OnUseItemHandler OnUseItem;

	public int AddItem(int infoId, int count = 1)
	{
		ItemInfo info = ItemInfoMgr.GetInfo(infoId);
		if (info != null)
		{
			Item item = GetItem(infoId);
			if (item == null)
			{
				if (info.type == 0)
				{
					ConstantData.physical += info.value * count;
				}
				else if (info.type == 4)
				{
					ConstantData.chips += info.value * count;
				}
				else if (info.type == 5)
				{
					if (GameManager.GType == GameType.Mission)
					{
						LevelDataIndex.CurrentLevel.shotCount += info.value * count;
					}
				}
				else
				{
					item = new Item(info, count);
					_items.Add(item);
				}
			}
			else
			{
				item.count += count;
			}
			Save();
			return item?.count ?? 0;
		}
		UnityEngine.Debug.LogError("item info id is invalid!");
		return 0;
	}

	public int UseItem(int infoId)
	{
		Item item = GetItem(infoId);
		if (item != null)
		{
			if (item.UsedBy())
			{
				item.count--;
				if (item.count == 0)
				{
					_items.Remove(item);
				}
				if (this.OnUseItem != null)
				{
					this.OnUseItem(item);
				}
			}
			Save();
			return item.count;
		}
		return 0;
	}

	[Serializable]
	public class ItemClass
	{
		public List<String> _items = new List<String>();
	}

	public Item GetItem(int infoId)
	{
		for (int i = 0; i < _items.Count; i++)
		{
			if (_items[i].info.id == infoId)
			{
				return _items[i];
			}
		}
		return null;
	}

	public void Save()
	{
		ItemClass itemClass = new ItemClass();
		foreach (Item item in _items)
		{
			itemClass._items.Add(item.ToJson());
		}
		string json = JsonUtility.ToJson(itemClass);
		PlayerPrefs.SetString("item.dat", json);
		PlayerPrefs.Save();
		/* string text = StreamTools.GetPersistentDataPath() + "item.dat";
		string path = text.Substring(0, text.LastIndexOf('/'));
		if (!Directory.Exists(path))
		{
			Directory.CreateDirectory(path);
		}
		using (FileStream output = new FileStream(text, FileMode.Create))
		{
			BinaryWriter writer = new BinaryWriter(output);
			Save(writer);
		} */
	}

	private void Save(BinaryWriter writer)
	{
		writer.Write(_items.Count);
		for (int i = 0; i < _items.Count; i++)
		{
			Item item = _items[i];
			writer.Write(item.info.id);
			writer.Write(item.count);
		}
	}

	public void Load()
	{
		string json = PlayerPrefs.GetString("item.dat");
		if (json.Equals("")) return;
		ItemClass itemClass = JsonUtility.FromJson<ItemClass>(json);
		_items.Clear();
		if (itemClass == null) return;
		foreach (string item in itemClass._items)
		{
			_items.Add(new Item(item));
		}
		/* string path = StreamTools.GetPersistentDataPath() + "item.dat";
		if (File.Exists(path))
		{
			using (FileStream input = new FileStream(path, FileMode.Open))
			{
				BinaryReader reader = new BinaryReader(input);
				Load(reader);
			}
		} */
	}

	private void Load(BinaryReader reader)
	{
		int num = reader.ReadInt32();
		for (int i = 0; i < num; i++)
		{
			int infoId = reader.ReadInt32();
			int count = reader.ReadInt32();
			AddItem(infoId, count);
		}
	}
}
